package jdk动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ：Xiaochen
 * @date ：Created in 2022/11/9 20:36
 * @description：
 * @modified By：
 * @version:
 */
public class ProxyFactory {

    //被代理的对象
    private Chuzu target;

    public ProxyFactory(Chuzu target) {
        this.target = target;
    }

    //获取代理对象
    public Chuzu getInstance(){
        //java中提供了一个代理类---该类可以动态生成代理对象
        ClassLoader loader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        InvocationHandler h=new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                intro();
                watch();
                Object result = method.invoke(target, args);
                return result;
            }
        };
        Object o = Proxy.newProxyInstance(loader,interfaces,h);
        return (Chuzu) o;
    }
    public void watch(){
        System.out.println("看房");
    }
    public void intro(){
        System.out.println("房源介绍");
    }
}